import { Table, Button, Select, Input, Popconfirm, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import {} from '@ant-design/icons';
import useGetData from 'hooks/useGetData';
import { getDeckList, delDeck, addDeck, changeDeck } from '@/api/modules/group';
import { getCardsList } from 'api/cards';
import { delTheCards, reloadTheCards } from 'api/relaction';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';
import { SUPER_ADMIN_AUTH_KEY } from '@conf';
import { dateFormat } from '@/utils/funcs';
import Prompt, { PromptMethods } from 'components/Prompt';
import EasyGroupModal, { ExsyGroupModalMethods } from 'components/Mahjong/easyGroupModal';

export default connect((state: any) => state.global)(function ({ authLevel }) {
	const { filterInfo, page, viewInfo, setFilterInfo, setPageIndex, setViewInfo, getData }: any = useGetData(
		getDeckList,
		{ name: '' },
		'list'
	);
	const [options, setoptions] = useState<any>([]);
	const [selects, setselects] = useState<any>([]);
	const [inedit, setinedit] = useState<boolean>(false);
	const [detail, setdetail] = useState<any>([]);
	const [expandedRowKeys, setexpandedRowKeys] = useState<any>([]);
	const promptRef = useRef<PromptMethods>(null);
	const previewRef = useRef<ExsyGroupModalMethods>(null);
	async function getDetail(expanded: boolean, { id: group_id }: { id: number }) {
		if (!expanded) return setexpandedRowKeys([]);
		const { list } = await getCardsList({ group_id, size: 999 });
		setdetail(list);
		setinedit(false);
		setTimeout(() => {
			setexpandedRowKeys([`row-${group_id}`]);
		});
	}

	const columns: any = [
		{ title: '编号', dataIndex: 'id', width: 60 },
		{ title: '名称', dataIndex: 'name', width: 160 },
		...(authLevel === SUPER_ADMIN_AUTH_KEY ? [{ title: '开发者', dataIndex: 'make', width: 100 }] : []),
		{ title: '创建时间', dataIndex: 'createtime', width: 160, render: (v: string) => dateFormat(v) },
		{
			title: '操作',
			width: 110,
			fixed: 'right',
			render: (e: any, { id, name }: any, index: number) => (
				<>
					<Button
						className=' ml-auto mr-1'
						onClick={() => {
							promptRef.current?.prompt({
								title: '编辑牌组',
								content: [
									{
										label: '请输入牌组名',
										name: 'name',
										rules: [{ required: true, message: '请输入牌组名！' }],
										type: 'text',
									},
								],
								onOk: async ({ name }: any) => {
									if (!name) return;
									await changeDeck(id, name);
									const { list } = viewInfo;
									Object.assign(list[index], { name });
									setViewInfo({ ...viewInfo, list: [...list] });
								},
							});
						}}>
						编辑
					</Button>
					<Popconfirm
						placement='topLeft'
						title='警告'
						description={`删除该牌组 ${name}？`}
						onConfirm={async () => {
							await delDeck(id);
							const { list } = viewInfo;
							list.splice(index, 1);
							setViewInfo({ ...viewInfo, list: [...list] });
						}}
						okText='Yes'
						cancelText='No'
						key={'del-' + id}>
						<Button>删除</Button>
					</Popconfirm>
				</>
			),
		},
		,
	];
	return (
		<div>
			<EasyGroupModal innerRef={previewRef} />
			<Prompt innerRef={promptRef} />
			<div className=' flex items-center mb-4'>
				<p>名称：</p>
				<Input
					style={{ width: 260 }}
					value={filterInfo.key}
					onChange={({ target: { value: name } }) => {
						setFilterInfo({ ...filterInfo, name }); // deep clone
					}}
					placeholder='关键词'
				/>
				<Button
					className=' ml-auto mr-1'
					onClick={() => {
						promptRef.current?.prompt({
							title: '创建牌组',
							content: [
								{
									label: '请输入牌组名',
									name: 'name',
									rules: [{ required: true, message: '请输入牌组名！' }],
									type: 'text',
								},
							],
							onOk: async ({ name }: any) => {
								if (!name) return;
								const { id } = await addDeck({ name });
								setViewInfo({ ...viewInfo, list: [{ id, name }, ...viewInfo.list] });
							},
						});
					}}>
					创建牌组
				</Button>
			</div>
			<Table
				dataSource={viewInfo.list || []}
				columns={columns}
				scroll={{ y: 'initial' }}
				rowKey={({ id }) => `row-${id}`}
				expandable={{
					expandedRowKeys,
					rowExpandable: () => true,
					expandedRowRender: ({ id: groupId }) => (
						<div className=' flex'>
							{inedit ? (
								<>
									<Select
										showSearch
										value={selects}
										placeholder='输入牌型名称搜索'
										className=' w-0 flex-1 h-32 mr-4'
										defaultActiveFirstOption={false}
										showArrow={false}
										filterOption={false}
										mode='multiple'
										onSearch={async (newValue: string) => {
											if (!newValue) return setoptions([]);
											const { list } = await getCardsList({ name: newValue, commond: 'getbyname' });
											setoptions(list.map(({ id, name }: any) => ({ value: id, label: name })));
										}}
										notFoundContent={'没有找到对应牌型'}
										options={options}
										onChange={setselects}
									/>
									<Button
										disabled={!selects || !selects.length}
										onClick={async () => {
											await reloadTheCards({ ids: selects, group_id: groupId });
											setinedit(false);
											getDetail(true, { id: groupId });
											message.success('添加成功');
										}}
										className='ml-auto'>
										提交
									</Button>
									<Button
										disabled={!options || !options.length}
										onClick={async () => {
											setselects(options.map(({ value }: any) => value));
										}}
										className='ml-auto'>
										all in
									</Button>
								</>
							) : (
								<>
									<div>
										{detail.length ? (
											detail.map(({ name, deck, id }: any, i: number) => (
												<div className=' flex mb-2'>
													<p className=' w-60'>{name}</p>
													<Button
														size='small'
														key={'view--' + id}
														onClick={() => {
															if (!deck || !deck.length) return message.error('不包含任何牌！');
															previewRef.current!.preview({ deck });
														}}>
														预览
													</Button>

													<Button
														size='small'
														key={'del--' + id}
														onClick={async () => {
															await delTheCards(id, groupId);
															detail.splice(i, 1);
															setdetail([...detail]);
														}}>
														删除
													</Button>
												</div>
											))
										) : (
											<p>暂未配置牌型！</p>
										)}
									</div>
									<Button
										className=' ml-auto'
										onClick={() => {
											setoptions(detail.map(({ id, name }: any) => ({ value: id, label: name })));
											setselects(detail.map(({ id }: any) => id));
											setinedit(true);
										}}>
										编辑
									</Button>
								</>
							)}
						</div>
					),
					onExpand: getDetail,
				}}
				pagination={{
					total: viewInfo.total,
					showTotal: (total) => `共 ${total} 项`,
					showSizeChanger: false,
					position: ['bottomLeft'],
					current: page,
					defaultPageSize: 15,
					onChange: (e) => setPageIndex(e),
				}}
			/>
		</div>
	);
});
